#include "my_stdio.h"
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdlib.h>

MyFILE* buyFile(int fd)
{
    MyFILE* f = (MyFILE*)malloc(sizeof(MyFILE));
    f->fileno=fd;
    f->flag=FLUSH_LINE;
    f->cap=SIZE;
    f->size=0;
    memset(f->outbuffer,0,sizeof(f->outbuffer));
    return f;
}

MyFILE* mfopen(const char *path, const char *mode)
{
    int fd = -1;
    if(strcmp(mode,"r")==0)
    {
        fd = open(path,O_RDONLY,0666);
    }
    else if(strcmp(mode,"w")==0)
    {

        fd = open(path,O_CREAT|O_WRONLY|O_TRUNC,0666);
    }
    else if(strcmp(mode,"a")==0)
    {

        fd = open(path,O_CREAT|O_WRONLY|O_APPEND,0666);
    }
    else{

    }
    if(fd<0)
    {
       // perror("open false\n");
        return NULL;
    }
    return buyFile(fd);
}
int mfwrite(const void *ptr, int num, MyFILE *stream)
{
    memcpy(stream->outbuffer+stream->size,ptr,num);
    stream->size+=num;
    if(stream->flag==FLUSH_LINE&&stream->outbuffer[stream->size-1]=='\n'&&stream->size>0)
    {
        mfflush(stream);
    }
    return num;
}
void mfflush(MyFILE *stream)
{
    if(stream->size>0)
    {
        write(stream->fileno,stream->outbuffer,stream->size);
        fsync(stream->fileno);
        stream->size=0;
    }
}
void mfclose(MyFILE *stream)
{
    if(stream->size>0)
        mfflush(stream);
    close(stream->fileno);
}

